/**
 * Copyright (c) 2019 xstgongyi.org
 * All rights reserved.
 */
package org.xstgongyi.eduaid.auth;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.xstgongyi.eduaid.dataobject.UserDO;
import org.xstgongyi.eduaid.service.UserService;

/**
 * @author oldcrane<br/>
 * @created 2019-05-16
 */
public class CustomRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// String loginName = (String) SecurityUtils.getSubject().getPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
		String loginName = token.getUsername();
		String passwd = new String((char[]) token.getCredentials());
		UserDO user = userService.getByLoginName(loginName);
		if (null == user) {
			throw new AccountException("登录失败，请检查账号密码");
		}
		String encryptedPasswd = AuthHelper.encodePassphrase(passwd, user.getSalt());
		boolean matched = user.getPassword().equals(encryptedPasswd);
		if (!matched) {
			throw new AccountException("登录失败，请检查账号密码");
		}

		return new SimpleAuthenticationInfo(token.getPrincipal(), passwd, getName());
	}

}
